package com.park.web.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class IPUtil {
	private static final String URL =  "http://ip.taobao.com/service/getIpInfo.php?ip=";
	private static Log log = LogFactory.getLog(IPUtil.class);
	/**
	 * 获取IP
	 * @return
	 */
	public static String getIP(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip=request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
		      ip = request.getHeader("WL-Proxy-Client-IP"); 
		    } 
		    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
		      ip = request.getHeader("HTTP_CLIENT_IP"); 
		    } 
		    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
		      ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
		    } 
		    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
		      ip = request.getRemoteAddr(); 
		    } 
		return ip;
	}
	
	/**
	 * unicode转换成中文
	 * @return
	 */
	 public static String decodeUnicode(String theString) {  
		 if(theString != null && !"".equals(theString) && !"error".startsWith(theString)){
			 int begin = theString.indexOf(":");
			 String code = theString.substring(begin+1,begin+2);
			 System.out.println(code);
			 if("0".equals(code)){
				  char aChar;  
				  int len = theString.length();  
				  StringBuffer outBuffer = new StringBuffer(len);  
				  for (int x = 0; x < len;) {  
				   aChar = theString.charAt(x++);  
				   if (aChar == '\\') {  
				    aChar = theString.charAt(x++);  
				    if (aChar == 'u') {  
				     int value = 0;  
				     for (int i = 0; i < 4; i++) {  
				      aChar = theString.charAt(x++);  
				      switch (aChar) {  
				      case '0':  
				      case '1':  
				      case '2':  
				      case '3':  
				      case '4':  
				      case '5':  
				      case '6':  
				      case '7':  
				      case '8':  
				      case '9':  
				       value = (value << 4) + aChar - '0';  
				       break;  
				      case 'a':  
				      case 'b':  
				      case 'c':  
				      case 'd':  
				      case 'e':  
				      case 'f':  
				       value = (value << 4) + 10 + aChar - 'a';  
				       break;  
				      case 'A':  
				      case 'B':  
				      case 'C':  
				      case 'D':  
				      case 'E':  
				      case 'F':  
				       value = (value << 4) + 10 + aChar - 'A';  
				       break;  
				      default:  
				       throw new IllegalArgumentException(  
				         "Malformed      encoding.");  
				      }  
				     }  
				     outBuffer.append((char) value);  
				    } else {  
				     if (aChar == 't') {  
				      aChar = '\t';  
				     } else if (aChar == 'r') {  
				      aChar = '\r';  
				     } else if (aChar == 'n') {  
				      aChar = '\n';  
				     } else if (aChar == 'f') {  
				      aChar = '\f';  
				     }  
				     outBuffer.append(aChar);  
				    }  
				   } else {  
				    outBuffer.append(aChar);  
				   }  
				  }  
				  return outBuffer.toString();  
			 }
		 }
		 return "";
	}  
	
	 /**
		 * 根据IP获取地理位置信息
		 * @return
		 */
	public static String getAddressByIP(String ip){ 
			StringBuffer result = new StringBuffer(); 
		  try{
			    URL url = new URL(URL + ip); 
			    URLConnection conn = url.openConnection(); 
			    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK")); 
			    String line = null; 
			    while((line = reader.readLine()) != null){ 
			      result.append(line); 
			    } 
			    reader.close(); 
			    log.error("根据IP:"+ip+"-->获取地理信息:"+result.toString());
			    return decodeUnicode(result.toString());
		  }catch( IOException e){ 
			  log.error("error:读取失败");
			  return "error:读取失败"; 
		  }
}
	
	public static String[] getDatas(String address){
		if(address != "" && address != null){
			try {
				JSONObject	object = JSONObject.parseObject(address);
				Object code = object.get("code");
				String[] addressInfo = null ;
				if("0".equals(code.toString())){
					JSONObject data = (JSONObject) object.get("data");
					String country = data.get("country").toString();//国家
					String countryId = data.get("country_id").toString();
					String area = data.get("area").toString();//区域
					String areaId = data.get("area_id").toString();
					String region = data.get("region").toString();//省
					String regionId = data.get("region_id").toString();
					String city = data.get("city").toString();//市
					String cityId = data.get("city_id").toString();
					String county = data.get("county").toString();//县或者区
					String countyId = data.get("county_id").toString();
					String isp = data.get("isp").toString();//省行政区号运营商
					String ispId = data.get("isp_id").toString();
					addressInfo = new String[]{country,countryId,area,areaId,region,regionId,city,cityId,county,countyId,isp,ispId};
				}
				return addressInfo;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return null;	
	}
	
	public static void main(String[] args) {
		System.out.println(getAddressByIP("61.136.234.253"));
	}
}
